package com.cc.common.exception

import com.cc.common.model.Results
import io.github.oshai.kotlinlogging.KotlinLogging
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.ModelAndView
import org.springframework.web.servlet.resource.NoResourceFoundException

/**
 * @author cc
 * @since 2024/1/21
 * @version 1.0
 */

private val logger = KotlinLogging.logger {}

@RestControllerAdvice
class ExceptionHandler {

    @ExceptionHandler(Exception::class)
    fun handleException(ex: Exception): Results<Any> {
        logger.error(ex) { "全局异常拦截: $ex" }
        return Results.Err("Server Error")
    }

    @ExceptionHandler(NoResourceFoundException::class)
    fun handleException(ex: NoResourceFoundException): ModelAndView {
        logger.error(ex) { "全局异常拦截: $ex" }
        return ModelAndView("error/404")
    }

    @ExceptionHandler(ServerException::class)
    fun handleException(ex: ServerException) = Results.Err(ex.msg)
}